package com.itboye.jigongbao.retrofit.base;

import android.app.Activity;
import android.net.ParseException;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import com.itboye.jigongbao.retrofit.util.DataEncryptionUtil;
import com.itboye.jigongbao.retrofit.util.ResponseListener;
import com.itboye.jigongbao.utils.LoadingDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeoutException;

import retrofit2.adapter.rxjava.HttpException;
import rx.Observer;

/**
 * BaseObserver
 * <p>
 * Created by Mr.w on 2017/12/11.
 * <p>
 * 版本      ${version}
 * <p>
 * 修改时间
 * <p>
 * 修改内容
 */


public class BaseObserver<E extends BaseResponse> implements Observer<E> {

    private ResponseListener responseListener;
    private Type expectReturnType;
    LoadingDialog progressDialog;
    private Activity activity;
    private boolean b;

    public BaseObserver(Activity activity, ResponseListener responseListener) {
        this.responseListener = responseListener;
        this.activity = activity;
        if (activity != null) {
            progressDialog = new LoadingDialog();
            progressDialog.setMsg("正在获取数据中");
            progressDialog.show(activity.getFragmentManager(), activity.getPackageName());
            progressDialog.setCancelable(true);
        }
    }

    @Override
    public void onCompleted() {
        try {
            if (activity != null) {
                progressDialog.dismiss();
            }
        }catch (Exception e){

        }

        Log.v("request", "complete");
    }

    @Override
    public void onError(Throwable throwable) {
        if (activity != null) {
            progressDialog.dismiss();
        }
        handleError(throwable);
    }

    @Override
    public void onNext(E response) {
        //得到的data
        String result = DataEncryptionUtil.decodeData(response.getData());
        int code = -1;
        JSONObject jsonObject = null;
        Object tClass = null;
        String msg = null;
        String data = null;
        long notify_id = 0;
        try {
            jsonObject = new JSONObject(result);
            code = jsonObject.getInt("code");
            msg = jsonObject.getString("msg");
            data = jsonObject.getString("data");
            notify_id = jsonObject.getLong("notify_id");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //处理data数据
        if (response.getType().equals("T")) {
            if (code == 0) {
                Gson gson = new Gson();
                tClass = gson.fromJson(data, expectReturnType);
                ResultEntity resultEntity = new ResultEntity(0, tClass, msg, notify_id);
                this.responseListener.success(resultEntity);
            } else if (code == -1) {

            }
        } else {
            ResultEntity resultEntity = new ResultEntity(-1, "请求失败" + "-->" + data, msg, 0);
            this.responseListener.fail(resultEntity);
        }

//            if (response.getType().equals("F")) {
//
//        } else if (response.getType().equals("E")) {
//
//        }
    }

    private void handleError(Throwable throwable) {
        String errorMsg = "请求失败";
        if (throwable instanceof UnknownHostException) {
            errorMsg = "没有联网哦";
        } else if (throwable instanceof HttpException) {
            errorMsg = "网络错误";
        } else if (throwable instanceof ConnectException) {
            errorMsg = "连接失败";
        } else if (throwable instanceof JsonParseException
                || throwable instanceof JSONException
                || throwable instanceof ParseException) {
            errorMsg = "数据解析有误";
        } else if (throwable instanceof TimeoutException) {
            errorMsg = "连接超时";
        } else if (throwable instanceof SocketTimeoutException) {
            errorMsg = "连接超时";
        } else {
            errorMsg = "other Exception ->" + throwable.getMessage();
        }
        errorMsg += throwable.getLocalizedMessage();
        ResultEntity resultEntity = new ResultEntity(-1, "请求失败", errorMsg, 0);
        this.responseListener.fail(resultEntity);
    }

    public BaseObserver<E> setExpectReturnType(Type classType) {
        this.expectReturnType = classType;
        return this;
    }

    public BaseObserver<E> showLoadingDialog(boolean b, Activity activity) {
        this.b = b;
        this.activity = activity;
        return this;
    }
}
